package com.easygoods.service;

import com.bestvike.stone.core.lang.Convert;
import com.bestvike.stone.core.lang.RandomUtils;
import com.bestvike.stone.core.lang.StringUtils;
import com.bestvike.stone.core.lang.URLUtils;
import com.bestvike.stone.spring.exception.BusinessException;
import com.bestvike.stone.spring.exception.ErrorCode;
import com.bestvike.stone.spring.service.BaseService;
import com.easygoods.dao.TinyUrlInfoDao;
import com.easygoods.entity.TinyUrlInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.server.ResponseStatusException;
import tk.mybatis.mapper.entity.Example;

/**
 * Created by 许崇雷 on 2019-02-12.
 */
@Service
public class TinyUrlService extends BaseService {
    @Autowired
    private TinyUrlInfoDao tinyUrlInfoDao;

    //url 转短位
    public String urlToTiny(String url) {
        Assert.hasText(url, "url can not be empty");

        //先从数据库中查询,如果存在直接返回
        final Example example = new Example(TinyUrlInfo.class);
        example.createCriteria().andEqualTo(TinyUrlInfo.URL, url);
        final TinyUrlInfo tinyUrlInfo = this.tinyUrlInfoDao.selectOneByExample(example);
        if (tinyUrlInfo != null)
            return tinyUrlInfo.getId();
        //不存在生成并返回
        String prefix = StringUtils.EMPTY;
        for (int i = 0; i < 3; i++) {
            for (String tiny : URLUtils.tiny(url, prefix, null)) {
                try {
                    TinyUrlInfo tinyUrlInfoInsert = new TinyUrlInfo();
                    tinyUrlInfoInsert.setId(tiny);
                    tinyUrlInfoInsert.setUrl(url);
                    tinyUrlInfoInsert.beforeInsert();
                    final int insert = this.tinyUrlInfoDao.insert(tinyUrlInfoInsert);
                    if (insert == 1)
                        return tiny;
                } catch (Exception ignored) {
                }
            }
            prefix += Convert.toString(RandomUtils.nextInt(0, 10));
        }
        throw new BusinessException(ErrorCode.ERROR_SERVER, "生成短 url 失败,请重试");
    }

    //短位转 url
    public String tinyToUrl(String tiny) {
        if (StringUtils.isEmpty(tiny))
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);

        final TinyUrlInfo tinyUrlInfo = this.tinyUrlInfoDao.selectByPrimaryKey(tiny);
        if (tinyUrlInfo == null)
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        return tinyUrlInfo.getUrl();
    }
}
